page = require('webpage').create()
fs = require 'fs'
page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) Gecko/20100101 Firefox/26.0'
page.settings.localToRemoteUrlAccessEnabled = true
page.viewportSize= { width: 1280, height:800 };
WEB_SITE = 'http://s.etao.com/'
JQUERY_URL = './lib/jquery-1.10.2.min.js'
OUTPUT_FLAG= '_OUT_'
URL_HASH_MAP = {}
CURRENT_URL = ''
page.onAlert = (msg)->
    console.log('ALERT: ' + msg)
page.onCallback = (data)->
    console.log('CALLBACK: ' + JSON.stringify(data))
page.onClosing = (closingPage)->
    console.log('CLOSING: ' + JSON.stringify(closingPage))
page.onConfirm = ()->
    console.log('CONFIRM: ' + msg)
page.onConsoleMessage = (msg, lineNum, sourceId)->
    if (msg.indexOf(OUTPUT_FLAG)==0)
        _msg = msg.replace(OUTPUT_FLAG,'')
        onConsoleMessage(_msg)
    else
        console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")')

page.onError = (msg, trace)->
    msgStack = ['ERROR: ' + msg];
    if trace && trace.length
        msgStack.push('TRACE:')
        trace.forEach (t)->
            msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''))
    console.error(msgStack.join('\n'))

page.onFilePicker = (oldFile)->
    console.log ('FILEPICKER: '+oldFile)
page.onInitialized = ()->
    console.log 'INITIALIZED'
page.onLoadFinished = (status)->
    console.log ('LOADFINISHED: '+status)
    if onLoadFinished and status is 'success'
        if URL_HASH_MAP[CURRENT_URL] is false
            URL_HASH_MAP[CURRENT_URL] = true
            onLoadFinished(status)  
page.onLoadStarted = ()->
    console.log 'LOADSTARTED'
    if !URL_HASH_MAP[CURRENT_URL]?
        URL_HASH_MAP[CURRENT_URL] = false;

page.onNavigationRequested = (url, type, willNavigate, main)->
    return
    console.log('TRYING TO NAVIGATE TO: ' + url);
    console.log('CAUSED BY: ' + type);
    console.log('WILL ACTUALLY NAVIGATE: ' + willNavigate);
    console.log('SENT FROM THE PAGE\'S MAIN FRAME: ' + main);

page.onPageCreated = (newPage)->
    console.log('A NEW CHILD PAGE WAS CREATED! ITS REQUESTED URL IS NOT YET AVAILABLE, THOUGH.')
page.onPrompt = (msg, defaultVal)->
    console.log 'PROMPT'
page.onResourceError = (resourceError)->
    console.log('UNABLE TO LOAD RESOURCE (#' + resourceError.id + 'URL:' + resourceError.url + ')');
    console.log('ERROR CODE: ' + resourceError.errorCode + '. DESCRIPTION: ' + resourceError.errorString)
page.onResourceReceived = (response)->
    return
    console.log('RESPONSE (#' + response.id + ', STAGE "' + response.stage + '"): ' + JSON.stringify(response))
page.onResourceRequested = (requestData, networkRequest)->
    return
    console.log('REQUEST (#' + requestData.id + '): ' + JSON.stringify(requestData))
page.onUrlChanged = (targetUrl)->
    CURRENT_URL = targetUrl
    URL_HASH_MAP[CURRENT_URL] = false
    console.log('NEW URL: ' + targetUrl)

onConsoleMessage = (data)->
    console.log 'OUT'
    reg = /_\w*_/
    key = reg.exec(data)
    if key
        key = key[0]
        data = data.replace(key,'')
    console.log 'key is: '+key
    switch key
        when '_SYS_'
            pos = JSON.parse(data)
            page.render ('./render/a.png')
            # console.log pos.left ,pos.top
            page.sendEvent('click',pos.left+20 ,pos.top+20)
            # console.log 'sendEvent pos',JSON.stringify(pos)
            # console.log 12132321321321
            # page.render ('./render/a.png')

onLoadFinished = (status)->
    console.log 'onLoadFinished'
    console.log CURRENT_URL,URL_HASH_MAP[CURRENT_URL]
    page.injectJs JQUERY_URL
    page.evaluate ()->
        ot = '_OUT_'
        act = '_SYS_'
        $('#J_searchIpt').val('手机')
        # $('#J_searchbox form').submit()
        s = JSON.stringify($('#J_searchbox input[type=submit]').offset())
        # console.log '11111111111',$('#J_searchbox input[type=submit]').val()
        console.log ot+act+s
    # pos = {"top":25,"left":351}
    # page.sendEvent('click',pos.left+20 ,pos.top+20)
    
    # phantom.exit()
run = ()->
    #打开 www.jd.com
    page.open WEB_SITE
        #插入 jquery.js
        # page.injectJs JQUERY_URL
    # phantom.exit()
        
    
#主函数入口
run()